<?php
namespace app\admin\controller;

use app\common\controller\Base;
use app\common\service\Menu as MenuService;
use think\Request;
use app\common\tool\Tool;

class Menu extends Base{

    /**
     * 菜单是独立的 不跟内容相关 这样扩展性更好 每个模块自己提供接口给菜单
     * @return \think\response\View
     */
    public function index(){

        $menuService = new MenuService();

        $menusTree = $menuService -> getMenusTree();

        return view('',['tree'=>$menusTree]);
    }

    public function add(){

        //父菜单  界面采用ajax好了 不弄那么多级别的 只弄三级就好了 那就直接展示了
        $menuService = new MenuService();

        $menusTree = $menuService -> getMenusTree();

        return view('',['tree'=>$menusTree]);
    }

    public function create(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request->only(['name','pid','url']);

        $menuService = new MenuService();

        $result = $menuService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }

    }

    public function edit(Request $request){
        $ids = $request -> only("id");
        if(count($ids)>1) $this->error("访问来源错误");

        $menuService = new MenuService();

        $menu = $menuService -> getAllMenus($ids)[0];

        $menusTree = $menuService -> getMenusTree();

        return view('',['menu'=>$menu,'tree'=>$menusTree]);
    }

    public function update(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['id','name','url']);

        $menuService = new MenuService();
        $result = $menuService ->update($data);

        if(1 == $result['state']) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }

        $id = $request->only(['id']);
        if(count($id) !== 1){
            $this->error("禁止批量操作");
        }
        $menuService = new MenuService();
        $count = $menuService -> delete($id);

        if($count){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }

    }
}